package com.demo.product.service.impl;

import com.demo.product.entity.Product;
import com.demo.product.mapper.ProductMapper;
import com.demo.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {
    
    private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
    
    @Autowired
    private ProductMapper productMapper;
    
    /**
     * 根据商品ID查询商品信息
     * 
     * @param id 商品ID
     * @return 商品信息
     */
    @Override
    public Product getProductById(Long id) {
        return productMapper.selectById(id);
    }
    
    /**
     * 扣减商品库存
     * 
     * @param productId 商品ID
     * @param count 扣减数量
     * @return 是否扣减成功
     */
    @Override
    @Transactional
    public boolean decreaseStock(Long productId, Integer count) {
        try {
            int result = productMapper.decreaseStock(productId, count);
            if (result > 0) {
                log.info("扣减库存成功，productId: {}, count: {}", productId, count);
                return true;
            } else {
                log.warn("扣减库存失败，可能库存不足，productId: {}, count: {}", productId, count);
                return false;
            }
        } catch (Exception e) {
            log.error("扣减库存异常，productId: {}, count: {}", productId, count, e);
            return false;
        }
    }
}